<template>
	<main-content
		:tableHeight.sync="tableHeight"
		:otherDependenComponents="otherDependenComponents"
	>
		<template slot="query">
			<el-form
				ref="form"
				:inline="true"
				:model="queryData"
				class="flex-warp-container"
			>
				<el-form-item
					:label="`${$t('common.belong_merchant')}:`"
					class="flex-row-container"
					label-width="77px"
				>
					<merchant-select
						v-model="queryData.merchantId"
					></merchant-select>
				</el-form-item>
				<el-form-item
					:label="`${$t('member.login_ip_member')}:`"
					class="flex-row-container"
					label-width="61px"
				>
					<el-input
						v-model="queryData.terminalInfo"
						size="medium"
						:placeholder="$t('risk.please_enter_login_Ip')"
						clearable
					></el-input>
				</el-form-item>
				<el-form-item
					:label="`${$t('member.ip_attribution')}:`"
					class="flex-row-container"
					label-width="77px"
				>
					<el-input
						v-model="queryData.ipAttribution"
						size="medium"
						:placeholder="$t('risk.please_enter_Ip_Address')"
						v-input="{ name: 'noNumEmpty' }"
						clearable
					></el-input>
				</el-form-item>
				<el-form-item
					:label="`${$t('common.createBy')}:`"
					class="flex-row-container"
					label-width="px"
				>
					<el-input
						v-model="queryData.createdBy"
						size="medium"
						:placeholder="$t('risk.please_enter_createdBy')"
						v-input="{ name: 'symbols' }"
						clearable
					></el-input>
				</el-form-item>
				<el-form-item
					:label="`${$t('common.createAt')}:`"
					class="flex-row-container"
					label-width="77px"
				>
					<el-date-picker
						v-model="registerTime"
						size="medium"
						:picker-options="pickerShortcut2"
						format="yyyy-MM-dd HH:mm:ss"
						type="datetimerange"
						range-separator="-"
						:start-placeholder="$t('common.start_date')"
						:end-placeholder="$t('common.end_date')"
						align="right"
						:clearable="false"
						value-format="timestamp"
						:default-time="defaultTime"
					></el-date-picker>
				</el-form-item>
				<el-form-item>
					<el-button
						type="primary"
						icon="el-icon-search"
						:disabled="loading"
						size="medium"
						@click="search"
					>
						{{ $t('common.search') }}
					</el-button>
					<el-button
						icon="el-icon-refresh-left"
						:disabled="loading"
						size="medium"
						@click="reset"
					>
						{{ $t('common.reset') }}
					</el-button>
					<el-button
						v-if="hasPermission('602011')"
						type="warning"
						icon="el-icon-folder"
						:disabled="loading"
						size="medium"
						@click="addOrEdit(1)"
					>
						{{ $t('common.add') }}
					</el-button>
				</el-form-item>
			</el-form>
		</template>
		<template slot="content">
			<el-table
				v-loading="loading"
				element-loading-spinner="el-icon-loading"
				border
				class="small-size-table"
				:data="tableData"
				highlight-current-row
				:header-cell-style="getRowClass"
				:max-height="tableHeight"
			>
				<el-table-column
					align="center"
					type="index"
					:label="`${$t('common.serial_number')}`"
					width="85"
				></el-table-column>
				<el-table-column
					prop="merchantId"
					align="center"
					:label="`${$t('common.belong_merchant')}`"
					show-overflow-tooltip
				>
					<template slot-scope="scope">
						{{ merchantFilter(scope.row.merchantId) }}
					</template>
				</el-table-column>
				<el-table-column
					prop="terminalInfo"
					align="center"
					:label="`${$t('member.login_ip_member')}`"
					show-overflow-tooltip
				>
					<template slot-scope="scope">
						<span>{{ scope.row.terminalInfo || '-' }}</span>
					</template>
				</el-table-column>
				<el-table-column
					prop="ipAttribution"
					align="center"
					:label="`${$t('member.ip_attribution')}`"
					show-overflow-tooltip
				>
					<template slot-scope="scope">
						<span>{{ scope.row.ipAttribution || '-' }}</span>
					</template>
				</el-table-column>

				<el-table-column
					prop="createdBy"
					align="center"
					:label="`${$t('common.createBy')}`"
					show-overflow-tooltip
				>
					<template slot-scope="scope">
						<span>{{ scope.row.createdBy || '-' }}</span>
					</template>
				</el-table-column>
				<el-table-column
					prop="createdAt"
					align="center"
					:label="`${$t('common.createAt')}`"
					show-overflow-tooltip
				>
					<template slot-scope="scope">
						<span>{{ scope.row.createdAt || '-' }}</span>
					</template>
				</el-table-column>
				<el-table-column
					prop="remarks"
					align="center"
					:label="`${$t('common.remark')}`"
					show-overflow-tooltip
				>
					<template slot-scope="scope">
						<span>{{ scope.row.remarks || '-' }}</span>
					</template>
				</el-table-column>

				<el-table-column
					prop="operating"
					align="center"
					:label="`${$t('common.actions')}`"
				>
					<template slot-scope="scope">
						<!-- <el-button
								v-if="hasPermission('813')"
								type="primary"
								icon="el-icon-edit"
								size="medium"
								@click="addOrEdit(2, scope.row)"
							>
								编辑
							</el-button> -->
						<el-button
							v-if="hasPermission('602012')"
							type="danger"
							icon="el-icon-delete"
							size="medium"
							@click="deleteIp(scope.row)"
						>
							{{ $t('common.delete') }}
						</el-button>
					</template>
				</el-table-column>
			</el-table>
			<!-- 分页 -->
			<el-pagination
				:total="total"
				:current-page.sync="pageNum"
				class="pageValue"
				background
				layout="total, sizes,prev, pager, next, jumper"
				:page-size="pageSize"
				:page-sizes="pageSizes"
				:pager-count="9"
				@current-change="handleCurrentChange"
				@size-change="handleSizeChange"
			></el-pagination>
		</template>
		<el-dialog
			:title="
				handleBtn === 1
					? $t('risk.add_login_ip_black_list')
					: $t('common.edit')
			"
			:visible.sync="addOrEditVisible"
			:destroy-on-close="true"
			width="30%"
			center
			:close="clearValidate"
		>
			<el-divider></el-divider>

			<el-form
				ref="formSub"
				:model="addOrEditData"
				:rules="rules"
				label-width="auto"
			>
				<el-form-item
					:label="`${$t('member.login_ip_member')}:`"
					prop="terminalInfo"
					:rules="[
						{
							required: true,
							validator: validateIp,
							trigger: 'blur'
						}
					]"
				>
					<el-input
						v-model.trim="addOrEditData.terminalInfo"
						maxlength="1000"
						autocomplete="off"
						:placeholder="$t('risk.please_enter_login_Ip')"
						clearable
						:disabled="handleBtn === 2"
						style="width:100%"
						oninput="value=value.replace(/\s+/g,'')"
					></el-input>
				</el-form-item>
				<el-form-item
					:label="`${$t('common.belong_merchant')}:`"
					prop="merchantId"
				>
					<merchant-select
						v-model="addOrEditData.merchantId"
						:placeholder="$t('common.components.select_merchant')"
						style="width:100%"
					></merchant-select>
				</el-form-item>
				<el-form-item v-if="handleBtn === 2" class="formTableBox">
					<div class="borderBox">
						<el-input
							v-model.trim="filterData"
							autocomplete="off"
							:placeholder="$t('member.username_placeholder')"
							clearable
							maxlength="11"
							style="width:300px"
							@clear="filterUser($event)"
							@input="filterUser($event)"
						></el-input>
						<el-table
							border
							max-height="280"
							size="mini"
							:data="editTableData"
							:header-cell-style="getRowClass"
						>
							<el-table-column
								align="center"
								type="index"
								:label="`${$t('common.serial_number')}`"
								width="75"
							></el-table-column>
							<el-table-column
								prop="userName"
								align="center"
								:label="`${$t('common.member_number')}`"
							></el-table-column>
							<el-table-column
								prop="lastLoginTime"
								align="center"
								:label="`${$t('risk.last_login_time')}`"
							>
								<template slot-scope="scope">
									<span>
										{{ scope.row.lastLoginTime || '-' }}
									</span>
								</template>
							</el-table-column>
							<el-table-column
								prop="loginLockStatus"
								align="center"
								:label="`${$t('common.login_lock_status')}`"
								width="75"
							>
								<template slot-scope="scope">
									<el-switch
										v-model="scope.row.loginLockStatus"
										:active-value="1"
										:inactive-value="0"
										@change="
											handleSwitch($event, scope.row)
										"
									></el-switch>
								</template>
							</el-table-column>
						</el-table>
					</div>
				</el-form-item>

				<el-form-item :label="`${$t('common.components.remark')}`">
					<el-input
						v-model="addOrEditData.remarks"
						type="textarea"
						maxlength="50"
						style="width:100%"
						v-input="{ name: 'noEmpty' }"
						:placeholder="$t('common.please_enter')"
						show-word-limit
					></el-input>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click="addOrEditVisible = false">
					{{ $t('common.cancel') }}
				</el-button>
				<el-button type="primary" @click="subAddOrEdit">
					{{ $t('common.save') }}
				</el-button>
			</div>
		</el-dialog>
	</main-content>
</template>

<script>
import list from '@/mixins/list'
import { routerNames } from '@/utils/consts'
import MainContent from '@/components/MainContent/index.vue'
import dayjs from 'dayjs'
const setSearchTime = () => [
	dayjs()
		.subtract(0, 'day')
		.startOf('day'),
	dayjs()
		.subtract(0, 'day')
		.endOf('day')
]
export default {
	name: routerNames.loginIPBlacklist,
	components: {
		MainContent
	},
	mixins: [list],
	data() {
		return {
			tableHeight: 480,
			otherDependenComponents: [],
			registerTime: setSearchTime(),
			queryData: {},
			tableData: [],
			handleBtn: 1,
			filterData: '',
			editTableData: [],
			addOrEditVisible: false,
			addOrEditData: {},
			detailTableData: [],
			rowData: []
		}
	},
	computed: {
		deviceTypeArr() {
			return this.globalDics.deviceType || []
		},
		rules() {
			const merchantId = [
				{
					required: true,
					message: this.$t('member.please_select_a_merchant'),
					trigger: 'blur'
				}
			]
			return {
				merchantId
			}
		}
	},
	methods: {
		loadData() {
			this.loading = true
			const create = this.registerTime || []
			const [startTime, endTime] = create
			this.tableData = []
			const params = {
				...this.queryData,
				typeId: 1,
				startCreatedAt: startTime
					? dayjs(startTime).format('YYYY-MM-DD HH:mm:ss')
					: undefined,
				endCreatedAt: endTime
					? dayjs(endTime).format('YYYY-MM-DD HH:mm:ss')
					: undefined,
				...this.getParams(params)
			}
			this.$api
				.getWindControlBlacklistquery(params)
				.then((res) => {
					this.loading = false
					if (res?.code === 200) {
						this.tableData = res.data.record || []
						this.total = res.data.totalRecord || 0
					}
				})
				.catch(() => {
					this.loading = false
				})

			setTimeout(() => {
				this.loading = false
			}, 1000)
		},
		reset() {
			this.pageNum = 1
			this.queryData = {}
			this.registerTime = setSearchTime()
			this.loadData()
		},
		// 新增或编辑
		addOrEdit(flag, row) {
			this.handleBtn = flag
			this.rowData = []
			this.editTableData = []
			this.addOrEditData = {}
			if (!this.$store.getters.isZk) {
				this.addOrEditData.merchantId = this.$store.getters.merchantInfo.id
			} else {
				this.addOrEditData = {
					terminalInfo: undefined,
					merchantId: undefined,
					remarks: undefined
				}
			}
			if (flag === 2) {
				this.filterData = ''
				const { id, terminalInfo, remarks, memberList, merchantId } = {
					...row
				}
				this.addOrEditData = { id, terminalInfo, remarks, merchantId }
				this.rowData = JSON.parse(JSON.stringify(memberList)) || []
				this.editTableData =
					JSON.parse(JSON.stringify(memberList)) || []
			}
			this.addOrEditVisible = true
		},
		validateIp(rule, value, callback) {
			const regular = /^((25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9])\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[0-9]))$/
			let arr = []
			if (value && value.includes('，')) {
				let str = ''
				str = value.replace(/，/g, ',')
				arr = str.split(',')
			} else if (value) {
				arr = value.split(',')
			} else {
				callback(this.$t('risk.required'))
			}
			if (arr.length > 0) {
				const flag = []
				for (let i = 0; i < arr.length; i++) {
					const ele = arr[i]
					if (ele && !regular.test(ele)) {
						flag.push(i + 1)
					}
				}
				if (flag.length) {
					callback(
						this.$t('risk.format_error') +
							flag.join(this.$t('risk.section')) +
							this.$t('risk.individual')
					)
				} else {
					callback()
				}
			}
		},
		filterUser(val) {
			const oldVal = this.rowData
			const newVal = []
			const reg = /[^A-Za-z0-9]/
			if (val && !reg.test(val)) {
				for (let i = 0; i < oldVal.length; i++) {
					const ele = oldVal[i]
					if (ele.userName.includes(val.trim())) {
						newVal.push(ele)
					}
				}
				this.editTableData = newVal
			} else {
				this.filterData = ''
				this.editTableData = oldVal
			}
		},
		// 登录锁定
		handleSwitch(val, row) {
			for (let i = 0; i < this.rowData.length; i++) {
				const ele = this.rowData[i]
				if (ele.id === row.id) {
					ele.loginLockStatus = val
				}
			}
		},
		clearValidate() {
			this.$refs.formSub.clearValidate()
		},
		deleteIp(val) {
			const params = {
				id: val.id
				// memberList: []
			}
			// for (let i = 0; i < val.memberList.length; i++) {
			// 	const ele = val.memberList[i]
			// 	ele.loginLockStatus = 0
			// 	params.memberList.push(ele)
			// }
			this.$confirm(
				`<strong>${this.$t(
					'risk.is_del_login_ip_black_tip'
				)}</strong><br/><strong style="color:#D9001B">${this.$t(
					'risk.del_risk_level_warning'
				)}</strong>`,
				{
					dangerouslyUseHTMLString: true,
					confirmButtonText: this.$t('common.confirm'),
					cancelButtonText: this.$t('common.cancel'),
					type: 'warning',
					customClass: 'positionIcon'
				}
			)
				.then(() => {
					const loading = this.$loading({
						lock: true,
						text: 'Loading',
						spinner: 'el-icon-loading',
						background: 'rgba(0, 0, 0, 0.7)'
					})
					this.$api
						.getWindControlBlacklistdel(params)
						.then((res) => {
							loading.close()
							if (res?.code === 200) {
								this.$message.success(
									this.$t('common.delete_success')
								)
							} else {
								this.$message({
									type: 'error',
									message: this.$t('common.delete_fail')
								})
							}
							setTimeout(() => {
								this.loadData()
							}, 1000)
						})
						.catch(() => {
							loading.close()
						})
				})
				.catch(() => {})
		},
		subAddOrEdit() {
			this.$refs.formSub.validate((valid) => {
				if (valid) {
					const loading = this.$loading({
						lock: true,
						text: 'Loading',
						spinner: 'el-icon-loading',
						background: 'rgba(0, 0, 0, 0.7)'
					})
					const terminalInfo = this.addOrEditData.terminalInfo.replace(
						/，/g,
						','
					)
					const params = {
						merchantId: this.addOrEditData.merchantId,
						typeId: 1,
						terminalInfo: terminalInfo,
						id: this.addOrEditData.id,
						remarks: this.addOrEditData.remarks,
						memberList:
							this.handleBtn === 1 ? undefined : this.rowData
					}
					const handleApi =
						this.handleBtn === 1
							? this.$api.getWindControlBlacklistadd
							: this.$api.getWindControlBlacklistupdate
					handleApi(params)
						.then((res) => {
							if (res?.code === 200) {
								loading.close()
								this.$message({
									message: `${
										this.handleBtn === 1
											? this.$t('common.add_success')
											: this.$t('common.modify') +
											  this.$t('common.success')
									}`,
									type: 'success'
								})
								setTimeout(() => {
									this.loadData()
								}, 1000)

								this.addOrEditVisible = false
							} else {
								loading.close()
								this.$message({
									message:
										res?.msg || this.$t('common.error'),
									type: 'error'
								})
							}
						})
						.catch(() => {
							loading.close()
						})
				}
			})
		}
	}
}
</script>

<style lang="scss" scoped>
.formTableBox {
	.borderBox {
		padding: 20px;
		border: 1px solid #dcdfe6;
		.el-input {
			width: 50%;
			margin-bottom: 15px;
		}
		.el-table {
			line-height: 32px;
		}
	}
}
</style>
